<?php

require_once 'BluesCoders/Event/Listener.php';

/**
 * Description of Front
 *
 * @author miho
 */
class BluesCoders_Controller_Front {

    const VIEW_RESOLVER_BEAN_ID = 'viewResolver';

    protected $_requestFactory;
    protected $_responseFactory;
    protected $_dispatcherMapper;
    protected $_context;
    protected $_viewResolver;

    public function setRequestFactory($value) {
        $this->_requestFactory = $value;
    }

    public function setResponseFactory($value) {
        $this->_responseFactory = $value;
    }

    public function setDispatcherMapper($value) {
        $this->_dispatcherMapper = $value;
    }

    public function  __construct() {
        $this->_initListeners();
    }

    protected function _initListeners() {
        BluesCoders_Event_Dispatcher::getIsntance()->addEventListener(
            BluesCoders_Application_Event::START_UP,
            new BluesCoders_Event_Listener($this, 'applicationStartUpHandler')
        );
    }

    public function applicationStartUpHandler(BluesCoders_Application_Event $event) {
        echo 'Starting up BluesCoders_Controller_Front';
        $this->_context = $event->getApplication()->getContext();
        $this->dispatch();
        return true;
    }

    public function dispatch() {
        //Dispatcher loop
        do{
            $dispatcher = $this->getDispatcher();
            $dispatcher->initializeContext($this->getContext());
            $result = $dispatcher->dispatch($this->getRequest(), $this->getResponse());
        }while($this->getRequest()->isForwarded());


        if(is_string($result)){
            $view = $this->getViewResolver()->getView($result);
        }elseif($result instanceof BluesCoders_Controller_ModelAndView){
            $view = $this->getViewResolver()->getView($result->getView());
            $view->addParams($result->getModel());
        }

        $view
            ->addParams($this->getRequest()->getParameters())
            ->addParams($this->getRequest()->getAttributes());


        $this->getResponse()->appendString($view->render());

        $this->getResponse()->flush();
    }

    public function getContext() {
        return $this->_context;
    }

    public function getDispatcher() {
        try{
            $dispatcherId = $this->_dispatcherMapper->getDispatcher($this->getRequest());
            return $this->getContext()->getBean($dispatcherId);
        }catch(Exception $e){
            throw new Exception('Getting of dispatcher failed. nested exception is: '.$e->getMessage());
        }
    }

    public function getRequest() {
        return $this->_requestFactory->getRequest();
    }

    public function getResponse() {
        return $this->_responseFactory->getResponse();
    }

    public function getViewResolver() {
        if($this->_viewResolver == null) {
            $this->_viewResolver = $this->getContext()->getBean(self::VIEW_RESOLVER_BEAN_ID);
        }

        return $this->_viewResolver;
    }


}
?>
